<script setup lang="ts">
import {onMounted, reactive, ref, UnwrapRef} from "vue";
import {useDataPublicStore} from '@/stores/dataPublicStore.ts';
import {useModifyOneAPI, useSaveOneEquipmentAPI} from '@/apis/equipment.ts'
import CameraCapture from "@/views/PublicCom/cameraCapture.vue";
import FileUpload from "@/views/PublicCom/ImageFilesUpload.vue";
import router from "@/router/index.js";
import {ComponentSize, FormInstance, FormProps, FormRules} from "element-plus";
import {useGetEquipmentTypeAPI} from "@/apis/equipmentType.js";


const equipmentTypeList=ref([]);

onMounted(async ()=>{
 const res= await useGetEquipmentTypeAPI(1,1000);
 equipmentTypeList.value=res.data;
})

const dataStore=useDataPublicStore();
const newEquipmentTypName=ref('');

const typeNameSelected=ref('')
const getEquipmentTypeName= (typeNameInDb: UnwrapRef<string>)=>{


  newEquipmentTypName.value=typeNameInDb[0]+':'+typeNameInDb[1];
  typeNameSelected.value=newEquipmentTypName.value;

  form.typeName=newEquipmentTypName.value;
}

const size=ref<ComponentSize>('default')
const labelPosition = ref<FormProps['labelPosition']>('right');

// 显示进度条配合函数
const format=(percentage:number)=>{
  return percentage===100?'100%':`${percentage}`
}

const formData=new FormData();
const form=reactive<RuleForm>({
  eqName:'',
  typeName:'',
  brand:'',
  pieces:'',
  model:'',
  description:'',
});

// 控制提交按钮的可操作性
const disableSwitch=ref(false);
const saveOneSummit= (formEl:FormInstance|undefined)=>{
  if (!formEl) return;
  formData.append('eqName',form.eqName);
  formData.append('typeName',form.typeName);
  formData.append('pieces',form.pieces);
  formData.append('brand',form.brand);
  formData.append('model',form.model);
  formData.append('description',form.description);
  if (dataStore.uploadFileList.length>0){
    dataStore.uploadFileList.forEach((item:File)=>{
      formData.append('eqPhotoList',item);
    });
  }
  if (dataStore.photoFileList.length>0){
    dataStore.photoFileList.forEach((item:File)=>{
      formData.append('eqPhotoList',item);
    })
  }

  formEl.validate( async (valid,fields)=>{
    if (valid){
      disableSwitch.value=true;
      await   useSaveOneEquipmentAPI(formData);
      await    useModifyOneAPI(formData);
      dataStore.setPhotoFiles([]);
      dataStore.setUploadFileList([]);
      dataStore.saveDataObject({});
      dataStore.setOnUploadProgress(0);
      await  router.push({path: '/home/equipment'});
    }
    else {
      console.log('error submit', fields);
    }
  })
}

// 表单校验
interface RuleForm {
  eqName:string
  brand:string
  model:string
  typeName:string
  pieces:string
  description:string
}

const ruleFormRef=ref<FormInstance>();
const rules=reactive<FormRules<typeof form>>({
  eqName:[
    {required:true,message:'必填项'},
    // { validator: (rule,value,callback)=>{
    //     // 使用正则表达式校验，正则表达式写在/ 正则表达式  /之间
    //     // 这里是：/      ^[A-Za-z0-9]([ A-Za-z0-9_-]*[A-Za-z0-9])?$     /
    //     if(!/^[\u4e00-\u9fa5]{3,64}$|^[\dA-Za-z_]{3,64}$/.test(value)){
    //       callback(new Error("输入中文或者英文、数字且字符数3~64"));
    //     }else{
    //       //校验通过
    //       callback();
    //     }
    //   },trigger:'blur'  }
  ],
  brand:[
    {required:true,message:'必填项'},
    // {validator:(rule, value, callback)=>{
    //     // 这里填写规则
    //     if (!/^[\u4e00-\u9fa5]{3,32}$|^[\dA-Za-z_]{3,32}$/.test(value)){
    //       callback(new Error('输入中文、英文或者数字，且总字符数3~32'))
    //     }else {
    //       callback();
    //     }
    //   } ,trigger:'blur'}
  ]
  ,model:[
    {required:true,message:'必填项'},
    // {validator:(rule, value, callback)=>{
    //     // 这里填写规则
    //     if (!/^[\u4e00-\u9fa5]{3,32}$|^[\dA-Za-z_]{3,32}$/.test(value)){
    //       callback(new Error('输入中文、英文或者数字，且总字符数3~32'))
    //     }else {
    //       callback();
    //     }
    //   } ,trigger:'blur'}
  ],
  typeName:[
    {required:true,message:'必填项'},
    // {validator:(rule, value, callback)=>{
    //     // 这里填写规则
    //     if (!/^[\u4e00-\u9fa5]{2,32}$|^[\dA-Za-z_]{2,32}$/.test(value)){
    //       callback(new Error('输入中文、英文或者数字，且总字符数3~32'))
    //     }else {
    //       callback();
    //     }
    //   } ,trigger:'blur'}
  ],
  pieces:[
    {required:true,message:'必填项'},
    // {validator:(rule, value, callback)=>{
    //     // 这里填写规则
    //     if (!/^[\u4e00-\u9fa5]{1,8}$|^[\a-zA-Z]{1,8}$/.test(value)){
    //       callback(new Error('输入中文或者英文，且总字符数1~8'))
    //     }else {
    //       callback();
    //     }
    //   } ,trigger:'blur'}
  ],
  description:[
    {required:true,message:'必填项'},
    {min:0,max:256,message:'描述总字符在0~256之间'}
  ],
})

const addEquipType=()=>{
  router.push({path:'/home/equipment/addEquipType'});
}

</script>

<template>
  <!--  进度条-->
  <el-progress :percentage="dataStore.onUploadProgress" :format="format"    :stroke-width="5" v-show="dataStore.onUploadProgress" style="margin: 0;padding: 0" ></el-progress>

  <!-- 面包屑 -->
  <div class="bread-container">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: `/` }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:`/home/equipment/`}" >设备列表</el-breadcrumb-item>
      <el-breadcrumb-item  >添加新设备</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <table class="mainTable">
    <tbody>
    <tr>
      <td style="background:#EFF6FF "><h3 style="color: #44a8da;background: #EFF6FF">新     设      备     信     息</h3></td>
    </tr>

    <tr>
      <td style="background: #EFF6FF">
        <el-form
            :model="form"
            label-width="auto"
            style="max-width: 90%;padding-left: 8%;padding-top: 2%"
            :label-position="labelPosition"
            :size="size"
            ref="ruleFormRef"
            :rules="rules"
        >
          <el-form-item label="设备名称" prop="eqName">
            <el-input v-model="form.eqName"/>
          </el-form-item>
          <el-form-item label="设备品牌" prop="brand">
            <el-input v-model="form.brand"/>
          </el-form-item>
          <el-form-item label="设备型号" prop="brand">
            <el-input v-model="form.model"/>
          </el-form-item>

          <el-form-item  label="设设备类型" prop="typeName">
            <el-input  disabled v-model="newEquipmentTypName"/>
            <!--        <el-input  disabled v-model="form.typeName"/>-->
            <el-cascader
                placeholder="请选择设备类型"
                :options="equipmentTypeList",
                @change="getEquipmentTypeName"
                v-model="newEquipmentTypName"
            />
            <el-button  @click="addEquipType" type="text" style="margin-left: 30px">没有对应类型？点击我</el-button>
          </el-form-item>
          <el-form-item label="设备数量单位" prop="pieces">
            <el-input v-model="form.pieces"/>
          </el-form-item>
          <el-form-item label="设备描述" prop="description">
            <el-input v-model="form.description"/>
          </el-form-item>
        </el-form>
      </td>
    </tr>


    <tr>
      <td style="font-family: 'Microsoft JhengHei',serif;font-size: larger;font-weight: bold;color: #44a8da" >图片资料上传</td>
    </tr>


    <tr>
      <td>
        <CameraCapture/>
      </td>
    </tr>


    <tr>
      <td>
        <FileUpload/>
      </td>
    </tr>


    <tr>
      <td colspan="2" style="background:#EFF6FF ">
        <el-button @click="saveOneSummit(ruleFormRef)" type="primary" :disabled="disableSwitch" style="margin-top: 1%;margin-bottom: 1%" >确认修改</el-button>
      </td>
    </tr>
    </tbody>
  </table>
</template>

<style scoped lang="scss">

.bread-container {
  padding: 25px 10px;
  margin-left: 10px;
}


.camera_outer {
  position: relative;
  overflow: hidden;
  // background: url("../../assets/img/user_0608_04.png") no-repeat center;
  background-size: 100%;

  video,
  canvas,
  .tx_img {
    -moz-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    transform: scaleX(-1);
  }

  .btn_camera {
    position: absolute;
    bottom: 4px;
    left: 0;
    right: 0;
    height: 50px;
    background-color: rgba(0, 0, 0, 0.3);
    line-height: 50px;
    text-align: center;
    color: #ffffff;
  }

  .bg_r_img {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
  }

  .img_bg_camera {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;

    img {
      width: 300px;
      height: 300px;
    }

    .img_btn_camera {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background-color: rgba(0, 0, 0, 0.3);
      color: #ffffff;

      .loding_img {
        width: 50px;
        height: 50px;
      }
    }
  }
}

.mainTable {
  margin-left: 6%;

}



.bread-container {
  padding: 25px 10px;
  margin-left: 10px;
}
.divTable {
  position: absolute;
  top: 150px;
  bottom: 0;
  left: 300px;
  right: 0;
  margin: auto;
}


table, td,tr{
  border: 1px solid #44a8da;
  text-align: center;
  border-spacing: 0;
  border-collapse: collapse;
  height: 45px;
  width: 80%;
}

.tableTitle{

  border-right: 0 none;
  border-left: 0 none;
  text-align: center;
  font-size: large;
  font-weight: bold;
}





</style>